// 封装购物车模块
import { defineStore } from 'pinia';
import { useUserStore } from './userStore';
import { computed } from 'vue';
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart';

//
export const useCartStore = defineStore('cart', {
  state: () => {
    return {
      cartList: [],
      userStore: useUserStore(),
    };
  },
  actions: {
    async updateNewList() {
      const res = await findNewCartListAPI();
      this.cartList = res.result;
    },
    async addCart(goods) {
      const isLogin = computed(() => this.userStore.userInfo.token); // 是否登录

      const { skuId, count } = goods;
      if (isLogin.value) {
        // 登录之后的加入购物车逻辑
        await insertCartAPI({ skuId, count });
        this.updateNewList();
      } else {
        // 添加购物车操作
        // 已添加过 - count+1
        // 没有添加过 - 直接push
        // 通过匹配传递过来的商品对象id，能不能在cartList中找到，找到了商品加1
        const item = this.cartList.find((item) => goods.skuId === item.skuId);
        if (item) {
          // 找到了
          item.count++;
        } else {
          this.cartList.push(goods);
        }
      }
    },

    async delCart(skuId) {
      const isLogin = computed(() => this.userStore.userInfo.token); // 是否登录
      if (isLogin.value) {
        //调用接口实现删除购物车
        await delCartAPI([skuId]);
        this.updateNewList();
      } else {
        // 1.找到删除项的下标值 - splice
        // const idx = this.cartList.findIndex((item) => {
        //   skuId === item.skuId;
        // });
        // this.cartList.splice(idx, 1);

        // 2.使用数组的过滤方法 - filter
        this.cartList = this.cartList.filter((item) => item.skuId !== skuId);
      }
    },

    singleCheck(skuId, selected) {
      // 通过skuId找到我要修改的那一项，然后把它的selected修改为传递过来的值
      const item = this.cartList.find((item) => item.skuId === skuId);
      item.selected = selected;
    },

    allCheck(selected) {
      // cartList中的每一项selected都设置为全选框状态
      this.cartList.forEach((item) => (item.selected = selected));
    },

    clearCart() {
      this.cartList = [];
    },
  },

  // 计算属性
  // 1.总的数量。所有项的count之和
  // 2.总价，所有项的count * price之和
  getters: {
    allCount: (state) => state.cartList.reduce((a, c) => a + c.count, 0),
    allPrice: (state) => state.cartList.reduce((a, c) => a + c.count * c.price, 0),
    // 是否全选
    isAll: (state) => state.cartList.every((item) => item.selected),

    // 已选择数量
    selectedCount: (state) =>
      state.cartList.filter((item) => item.selected).reduce((a, c) => c.count + a, 0),

    // 已选择商品合计
    selectedPrice: (state) =>
      state.cartList.filter((item) => item.selected).reduce((a, c) => c.count * c.price + a, 0),
  },
  persist: true,
});
